const express = require('express')

// 文件上传相关
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

// 静态资源
app.use(express.static('./uploads'))

// 跨域
const cors = require('cors')
app.use(cors())

// 解析数据
app.use(express.urlencoded({extended: false}))

// 封装res.send()方法
app.use((req, res, next) => {
    res.cc = function(err, code = 400) {
        res.send({
            code,
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

// 解析token
const secretKey = 'rent_car' 
const expressJWT = require('express-jwt')
app.use(expressJWT({secret: secretKey}).unless({path: [/^\/car\//]}))

// 引入路由
// 后台管理员
const adminRouter = require('./router/admin')
app.use('/car', adminRouter)
// 用户
const userRouter = require('./router/user')
app.use('/car', userRouter)
// 城市
const cityAreaRouter = require('./router/cityArea')
app.use('/car', cityAreaRouter)
// 停车场
const parkingRouter = require('./router/parking')
app.use('/car', parkingRouter)
// 品牌
const brandRouter = require('./router/brand')
app.use('/car', brandRouter)
// 文件上传
const uploadRouter = require('./router/upload')
app.use('/car', uploadRouter)
// 车辆
const carRouter = require('./router/car')
app.use('/car', carRouter)
// 订单
const orderRouter = require('./router/order')
app.use('/car', orderRouter)


// 错误处理，必须在所有路由之后
app.use((err, req, res, next) => {
    // token解析失败导致的错误
    if (err.name === 'UnauthorizedError') return res.cc('身份认证失败')
    // 其他原因导致的错误
    // res.cc('未知错误')
    res.cc(err)
    
})

app.listen(3007, () => {
    console.log("server is running at http://127.0.0.1:3007");
})